﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.Dependencies;
using Unity;

namespace MaCodeBase.UnityExtend
{
    /// <summary>
    /// 接替程序,完成依赖注入
    /// 
    ///  Web API 配置和服务
    ///   config.DependencyResolver = new UnityDependencyResolver(ContainerFactory.BuildContainer());
    /// </summary>
    public class UnityDependencyResolver : IDependencyResolver
    {
        private IUnityContainer _UnityContainer = null;
        public UnityDependencyResolver(IUnityContainer container)
        {
            _UnityContainer = container;
        }
        public IDependencyScope BeginScope()
        {
            return new UnityDependencyResolver(this._UnityContainer.CreateChildContainer());
        }

        public void Dispose()
        {
            this._UnityContainer.Dispose();
        }

        public object GetService(Type serviceType)
        {
            try
            {
                return ContainerFactory.BuildContainer().Resolve(serviceType);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return null;
            }
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            try
            {
                return ContainerFactory.BuildContainer().ResolveAll(serviceType);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return null;
            }
        }
    }
}
